﻿using HZY.Framework.AutoRegisterIOC;
using HZY.Framework.Core.Utils;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Threading;
using Wpf.Ui;
using Wpf.Ui.Controls;
using XC.EFCore;
using XC.Infrastructure;
using XC.Infrastructure.SerilogUtil;
using XC.WpfHost.Extensions;
using XC.WpfHost.Services;
using XC.WpfHost.Services.Contracts;
using XC.WpfHost.ViewModels;
using XC.WpfHost.Views;
using XC.WpfHost.Views.Pages;
namespace XC.WpfHost
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {
        private IConfiguration configuration { get; set; }
        private static readonly IHost _host = Host.CreateDefaultBuilder().LogUtilBuild()
     .ConfigureAppConfiguration(c =>
     {
         c.SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json",true,true);
     })
     .ConfigureServices(
         (context, services) =>
         {

             // App Host
             services.AddHostedService<ApplicationHostService>();

             // Page resolver service
             services.AddSingleton<IPageService, PageService>();

             // Theme manipulation
             services.AddSingleton<IThemeService, ThemeService>();

             services.AddSingleton<ISnackbarService, SnackbarService>();

             // TaskBar manipulation
             services.AddSingleton<ITaskBarService, TaskBarService>();

             // Service containing navigation, same as INavigationWindow... but without window
             services.AddSingleton<INavigationService, NavigationService>();
 
             // Main window with navigation
             services.AddSingleton<IWindow,LoginWin>();

             services.AddSingleton<LoginWinWiewModel>();

             services.AddSingleton<INavigationWindow, MainWindow>();

             services.AddSingleton<MainWindowViewModel>();

             // Views and ViewModels
             services.AddSingleton<DashboardPage>();
             services.AddSingleton<SettingsPage>();
             services.AddSingleton<SettingsViewModel>();

             services.AddSingleton<Home>();
             services.AddSingleton<HomeViewModel>();

             // All other pages and view models
             services.AddTransientFromNamespace("XC.WpfHost.Views", GalleryAssembly.Asssembly);
             services.AddTransientFromNamespace("XC.WpfHost.ViewModels", GalleryAssembly.Asssembly);
             services.AddOptions();
             // Configuration
             services.Configure<AppConfiguration>(context.Configuration.GetSection(nameof(AppConfiguration)));
             var appConfiguration = new AppConfiguration(context.Configuration);
             var prefixString = appConfiguration.Configs.Namespace + ".";
             //扫描服务自动化注册
             services.AddAutoRegisterIOC(AssemblyUtil.GetAssemblyList(prefixString).ToList());

             services.AddEntityFramework(appConfiguration);

             services.AddMemoryCache();
         }
     )
     .Build();
       

        /// <summary>
        /// Gets registered service.
        /// </summary>
        /// <typeparam name="T">Type of the service to get.</typeparam>
        /// <returns>Instance of the service or <see langword="null"/>.</returns>
        public static T? GetService<T>()
            where T : class
        {
            return _host.Services.GetService(typeof(T)) as T;
        }

        /// <summary>
        /// Occurs when the application is loading.
        /// </summary>
        private async void OnStartup(object sender, StartupEventArgs e)
        {
            await _host.StartAsync();
        }

        /// <summary>
        /// Occurs when the application is closing.
        /// </summary>
        private async void OnExit(object sender, ExitEventArgs e)
        {
            await _host.StopAsync();

            _host.Dispose();
        }

        /// <summary>
        /// Occurs when an exception is thrown by an application but not handled.
        /// </summary>
        private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            LogUtil.Log.Error($"错误信息：{e.Exception.Message},栈信息：{e.Exception.StackTrace}");
            //var _snackbarService = GetService<ISnackbarService>();
            //if (_snackbarService != null)
            //{
            //    ControlAppearance _snackbarAppearance = ControlAppearance.Danger;

            //    _snackbarService.Show("提示", e.Exception.Message, _snackbarAppearance, null, TimeSpan.FromSeconds(5));
            //}
            // For more info see https://docs.microsoft.com/en-us/dotnet/api/system.windows.application.dispatcherunhandledexception?view=windowsdesktop-6.0
        }
    }

}
